package com.z1.core.web.util.mybatis.shard.strategy;

import org.apache.commons.lang.StringUtils;

import com.google.code.shardbatis.strategy.ShardStrategy;

public abstract class RemainderStrategy extends ShardStrategy {

	//表后缀长度：默认为2位
	private Integer driverLength = 2;
	public Integer getDriverLength() {
		return driverLength;
	}
	public void setDriverLength(Integer driverLength) {
		this.driverLength = driverLength;
	}

	//驱动值：用于对指定数据取余的除数值
	private Integer driver = 16;
	public void setDriver(Integer driver) {
		this.driver = driver;
	}
	public Integer getDriver() {
		return driver;
	}
	
	/**
	 * 得到实际表名
	 * @param baseTableName 基础表
	 * @param params mybatis执行某个statement时使用的参数
	 * @param mapperId mybatis配置的statement id
	 * @return
	 */
	@Override
	public String[] getTargetTableNames(String baseTableName, Object params, String mapperId) {
        Integer[] codes = getCodes(params, mapperId);
        if (null != codes) {
        	String[] tables = new String[codes.length];
        	for (int i = 0; i < tables.length; i++) {
        		if (null == codes[i]) { continue; }
        		int index = Math.abs(codes[i] % getDriver());
        		String strIndex = StringUtils.leftPad(String.valueOf(index), getDriverLength(), '0');
        		tables[i] = baseTableName + "_" + strIndex;
        	}
        	return tables;
        }
        return new String[] { baseTableName };
	}
	
	protected abstract Integer[] getCodes(Object params, String mapperId);

}
